package com.kgc.cgconsumer.Controller;

import com.kgc.basic.util.ResponseMsg;
import com.kgc.cgconsumer.service.ImportExportFeign;
import com.kgc.cgconsumer.service.PurchaseInvoiceFeign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Map;

@RestController
@RequestMapping("/purchaseInvoice")
@CrossOrigin
public class PurchaseInvoiceController {
    private Logger logger = LoggerFactory.getLogger(PurchaseInvoiceController.class);

    @Autowired
    private PurchaseInvoiceFeign purchaseInvoiceFeign;

    @Autowired
    private ImportExportFeign importExportFeign;

    @RequestMapping("selectPurchaseInvoiceByPage")
    public ResponseMsg selectPurchaseInvoiceByPage(@RequestBody Map<String, Object> map) {
        logger.info("consumer PurchaseInvoiceController selectPurchaseInvoiceByPage map:{}", map);
        return purchaseInvoiceFeign.selectPurchaseInvoiceByPage(map);
    }

    @RequestMapping("insertPurchaseInvoice")
    public ResponseMsg insertPurchaseInvoice(@RequestBody Map<String, Object> map) {
        logger.info("consumer PurchaseInvoiceController insertPurchaseInvoice map:{}", map);
        return purchaseInvoiceFeign.insertPurchaseInvoice(map);
    }

    @RequestMapping("selectPurchaseInstoreByPid")
    public ResponseMsg selectPurchaseInstoreByPid(@RequestParam("supplierId") String supplierId) {
        logger.info("consumer PurchaseInvoiceController selectPurchaseInstoreByPid supplierId:{}", supplierId);
        return purchaseInvoiceFeign.selectPurchaseInstoreByPid(Integer.parseInt(supplierId));
    }

    @RequestMapping("selectPurchaseInstoreDetailByInstoreCode")
    public ResponseMsg selectPurchaseInstoreDetailByInstoreCode(@RequestParam("instoreCode") String instoreCode) {
        logger.info("consumer selectPurchaseInstoreDetailByInstoreCode instoreCode:{}", instoreCode);
        return purchaseInvoiceFeign.selectPurchaseInstoreDetailByInstoreCode(instoreCode);
    }

    //回显（主表）
    @RequestMapping("selectPurchaseInvoiceByCode")
    public ResponseMsg selectPurchaseInvoiceByCode(@RequestParam("code") String code) {
        logger.info("consumer PurchaseInvoiceController selectPurchaseInvoiceByCode code:{}", code);
        return purchaseInvoiceFeign.selectPurchaseInvoiceByCode(code);
    }

    //回显（明细表）
    @RequestMapping("selectPurchaseInvoiceDetailByCode")
    public ResponseMsg selectPurchaseInvoiceDetailByCode(@RequestParam("invoiceCode") String invoiceCode) {
        logger.info("consumer PurchaseInvoiceController selectPurchaseInvoiceDetailByCode invoiceCode:{}", invoiceCode);
        return purchaseInvoiceFeign.selectPurchaseInvoiceDetailByCode(invoiceCode);
    }

    @RequestMapping("deletePurchaseInvoice")
    public ResponseMsg deletePurchaseInvoice(@RequestParam("id") String id) {
        logger.info("consumer deletePurchaseInvoice id:{}", id);
        return purchaseInvoiceFeign.deletePurchaseInvoice(Integer.parseInt(id));
    }

    @RequestMapping("deleteBeforeUpdate")
    public ResponseMsg deleteBeforeUpdate(@RequestParam("code") String code) {
        logger.info("consumer deleteBeforeUpdate code:{}", code);
        ResponseMsg msg = purchaseInvoiceFeign.deletePurchaseInvoiceByCode(code);
        ResponseMsg msg1 = purchaseInvoiceFeign.deletePurchaseInvoiceDetailByCode(code);
        msg1.setData(msg);
        return msg;
    }

    @RequestMapping(value = "/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseMsg importInfo(@RequestPart("file") MultipartFile file) {
        logger.info("consumer PurchaseInvoiceController importInfo fileName:{}", file.getOriginalFilename());
        return importExportFeign.importInfo(file, "com.kgc.cgapi.pojo.PurchaseInvoice", "code", "PurchaseInvoiceerviceImpl");
    }

    @RequestMapping(value = "/template", method = RequestMethod.GET)
    public void downTemplate(HttpServletResponse response) {
        logger.info("consumer PurchaseInvoiceController downTemplate is start...");
        try {
            ResponseMsg responseMsg = importExportFeign.downLoadTemplate("com.kgc.cgapi.pojo.PurchaseInvoice");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] templateData = Base64.getDecoder().decode(base64Data);   //解码

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("采购发票信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(templateData);
            } else {
                logger.error("下载模板失败, status: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer PurchaseInvoiceController downTemplate is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping(value = "/export")
    public void exportPurchaseInvoice(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        logger.info("consumer PurchaseInvoiceController exportPurchaseInvoice params:{}", map);
        try {
            ResponseMsg responseMsg = importExportFeign.exportEntities(map, "com.kgc.cgapi.pojo.PurchaseInvoice", "");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] exportData = Base64.getDecoder().decode(base64Data);

                //设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("采购发票信息表.xlsx", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(exportData);
            } else {
                logger.error("导出失败, msg: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer PurchaseInvoiceController exportPurchaseInvoice is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping(value = "/print", method = RequestMethod.POST)
    public void printPurchaseInvoice(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        logger.info("consumer PurchaseInvoiceController printPurchaseInvoice params:{}", map);
        try {
            logger.info("Map: {}", map);
            ResponseMsg responseMsg = importExportFeign.printEntitiesToPDF(map, "com.kgc.cgapi.pojo.PurchaseInvoice", "");
            if ("200".equals(responseMsg.getCode())) {
                String base64Data = (String) responseMsg.getData();
                byte[] pdfData = Base64.getDecoder().decode(base64Data);

                response.setContentType("application/pdf");
                response.setCharacterEncoding("UTF-8");
                String filename = URLEncoder.encode("采购发票信息表.pdf", "UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filename);

                response.getOutputStream().write(pdfData);
            } else {
                logger.error("打印失败, msg: {}", responseMsg.getMsg());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (IOException e) {
            logger.error("consumer PurchaseInvoiceController printPurchaseInvoice is error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
